<?php
/**
 * 后台基类
 */

namespace app\admin\controller;

use think\Controller;

class Base extends Controller
{
    /**
     * page
     * @var string
     */
    public $page = '';
    /**
     * 每页显示多少条
     * @var string
     */
    public $size = '';
    /**
     * 查询条件的起始值
     * @var int
     */
    public $from = 0;
    /**
     * 自定义model
     * @var string
     */
    public $model = '';
    /**
     * 初始化的方法
     */
    public function _initialize(){
        //判断用户是否登录
        $isLogin = $this->isLogin();
        if(!$isLogin){
            return $this->redirect('login/index');
        }
    }

    /**
     * 判断是否登陆
     * @return bool
     */
    public function isLogin(){
        $username =  session(config('admin.session_user'),'' ,config('admin.session_user_scope'));
        if($username && $username->id){
            return true;
        }
        return false;
    }

    /**
     * 获取分页的page  size内容
     */
    public function getPageAndSize($data){
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['size'] : config('paginate.list_rows');
        $this->from = ($this->page -1)*$this->size;
    }

    /**
     * 通用删除方法
     * @param int $id
     */
    public function delete($id = 0){
        if (!intval($id)){
            return $this->result('', 0, 'ID不合法');
        }
        //当数据表与控制器名不一致时 采用$this->model自定义指定
        //如：Admin控制器中add方法指定为AdminUser数据表
        //       $this->model = 'AdminUser';
        $model = $this->model ? $this->model :request()->controller();
//        halt($model);
        try{
            $res = model($model)->save(['status' => -1],['id' => $id]);
        }catch (\Exception $e){
            return $this->result('', 0, $e->getMessage());
        }
        if($res){
//            echo 1;
            return $this->result(['jump_url' => $_SERVER['HTTP_REFERER']], 1, 'OK');
        }
            return $this->result('', 0, '删除失败' );
    }
    /**
     * 通用化修改状态
     */
    public function status() {
        $data  = input('param.');
        // tp5  validate 机制 校验  小伙伴自行完成 id status

        // 通过id 去库中查询下记录是否存在
        //model('News')->get($data['id']);

        $model = $this->model ? $this->model : request()->controller();

        try {
            $res = model($model)->save(['status' => $data['status']], ['id' => $data['id']]);
        }catch(\Exception $e) {
            return $this->result('', 0, $e->getMessage());
        }

        if($res) {
            return $this->result(['jump_url' => $_SERVER['HTTP_REFERER']], 1, 'OK');
        }
        return $this->result('', 0, '修改失败');
    }
}